// pages/cart/cart.js
Page({
  data: {
    allChecked:false,
    total:0,
  },

  onLoad: async function (options) {
    const module = await import("../../utils/urls.js");
    const res = await module.cart.cartUrl();  
    this.totalPrice(res.data.results)
    this.setData({cart:res.data.results});
    this.reverse();
    this.total()
  },
  changeNum(event){
    let {operation,id} = event.currentTarget.dataset;
    let cart = this.data.cart;
    cart.forEach(item=>{
      if(item.id == id){
        item.count.num += Number(operation);
        item.checked = true;
        if(item.count.num<=0){
          item.count.num = 0;
          item.checked = false;
        }
      }
    })
    this.totalPrice(cart);
    this.setData({cart});
    this.reverse();
    this.total();
  },
  totalPrice(obj){
    obj.forEach(item=>{
      item.totalPrice = item.price * item.count.num;
    })
  },
  reverse(){
    let {cart} = this.data;
    let reverse = cart.every(item=>{
      return item.checked == true;
    })
    this.setData({allChecked:reverse})
  },
  onChange(event){
    let {id} = event.currentTarget.dataset;
    let {cart} = this.data;
    cart.forEach(item=>{
      if(item.id == id){
        item.checked = !item.checked;
      }
    })
    this.setData({cart});
    this.reverse();
    this.total();
  },
  total(){
    let {cart} = this.data;
    let total = 0;
    cart.forEach(item=>{
      if(item.checked == true){
        total += item.totalPrice;
      }
    })
    this.setData({total});
  },
  checkAll(){
    let {cart,allChecked} = this.data;
    allChecked = !allChecked;
    cart.forEach(item=>{
      item.checked = allChecked;
    })
    this.setData({cart,allChecked});
    this.total();
  }
})